<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true">
      <el-form-item label="表名称" prop="tableName">
        <el-select style="width: 300px"
                   v-model="queryParams.tableName"
                   placeholder="请选择表名称"
                   clearable
                   @change="tableSelect"
        >
          <el-option
            v-for="(item, index) in tableOptions"
            :key="index"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        <el-button type="success" plain icon="el-icon-upload" size="mini" @click="handleSyc">同步</el-button>
      </el-form-item>
    </el-form>
    <el-table @row-click="clickRow" ref="table" :data="dbTableList" @selection-change="handleSelectionChange" v-if="shows" :render-header="linefeed">
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column  v-for="item in tableHead" :label="item.label" :property="item.property">
      </el-table-column>
    </el-table>
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <!-- 数据同步对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1000px" append-to-body @close="clo">
      <div>
        <el-form :inline="true" ref="form" :model="form" :rules="rules" label-width="200px">
          <el-row>
            <el-form-item label="数据库地址" prop="adress">
              <el-input v-model="form.adress" placeholder="请输入数据库地址" style="width: 217px" required/>
            </el-form-item>
            <el-form-item label="源数据库用户名" prop="user">
              <el-input v-model="form.user" placeholder="请输入源数据库用户名" style="width: 217px" required/>
            </el-form-item>
          </el-row>
          <el-row>
            <el-form-item label="源数据库密码" prop="password">
              <el-input type="password" v-model="form.password" placeholder="请输入源数据库密码" style="width: 217px" required/>
            </el-form-item>
          </el-row>
          <el-row>
            <el-form-item label="源数据库名称" prop="checkedDatabaseNames">
              <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">全选</el-checkbox>
              <div style="margin: 15px 0;"></div>
              <el-checkbox-group v-model="form.checkedDatabaseNames" @change="handleCheckedTablesChange">
                <el-checkbox v-for="table in checktableNames" :label="table" :key="table">{{table}}</el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-row>
          <el-row>
            <el-form-item label="同步方式" prop="checkedType">
              <el-radio-group v-model="form.checkedType" @change="sycChange">
                <el-radio label="1">全量同步</el-radio>
                <el-radio label="2">按条件同步</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-row>
          <el-row>
            <el-form-item label="同步Id起始位置" prop="startSysId">
              <el-input-number v-model="form.startSysId" controls-position="right" style="width: 217px;" :disabled="dis"/>
            </el-form-item>
            <el-form-item label="同步Id结束位置" prop="endSysId">
              <el-input-number v-model="form.endSysId" controls-position="right" style="width: 217px;" :disabled="dis"/>
            </el-form-item>
          </el-row>
          <el-row>
            <el-form-item label="同步结果">
              <el-input type="textarea" v-model="result" :readonly="true" style="width: 645px;" :autosize="{ minRows: 6, maxRows: 10}"></el-input>
            </el-form-item>
          </el-row>
          <el-row>
            <el-form-item label="同步进度">
            </el-form-item>
            <el-progress :text-inside="true" style="width: 67%;margin-left: 21%;margin-top: -50px;" :stroke-width="20" :percentage="0" status="success"></el-progress>
          </el-row>
        </el-form>
        <div slot="footer" class="dialog-footer" style="text-align: center;margin-top: 50px;">
          <el-button type="primary" @click="submitForm" :disabled="sycDisabled">同 步</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import { listMdlsTable, listMdlsColumn, allList, connectCount, maxSysId, connectDatabase, sycDataBaseResource } from "@/api/tool/gen";
  const checkedtableOptions=['Engineeren', 'Rmgb', 'Gcbbao', 'Gcbxxzyqk', 'Gcbxxzyts', 'Tyzbbzbz'];
  export default {
    data() {
      return {
        // 遮罩层
        visible: false,
        // 选中数组值
        tables: [],
        // 选中数组
        sysids: [],
        // 总条数
        total: 0,
        // 表头
        tableHead: [],
        // 非多个禁用
        multiple: true,
        isPrint: false,
        sycDisabled: false,
        // 弹出层标题
        title: "数据同步",
        shows: false,
        dis:true,
        // 是否显示弹出层
        open: false,
        // 显示搜索条件
        showSearch: true,
        // 表数据
        dbTableList: [],
        //查询表名称
        tableOptions:[],
        //表名称
        oldtableOptions:[],
        //源字段信息
        columnOptions:[],
        //同步结果
        result: null,
        //待导入字段信息
        newColumnOptions:[],
        checkAll: false,
        checktableNames:checkedtableOptions,
        isIndeterminate: true,
        //待导入数据库表
        newtableOptions: [{
          value: 'mdls_books_basic',
          label: 'mdls_books_basic'
        }, {
          value: 'mdls_file',
          label: 'mdls_file'
        },{
          value: 'mdls_image',
          label: 'mdls_image'
        },{
          value: 'mdls_periodical_basic',
          label: 'mdls_periodical_basic'
        }],
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          tableName: undefined,
          tableComment: undefined
        },
        formData: {
        },
        //表参数
        tableParams:{
          pageNum: 1,
          pageSize: 100
        },
        //form表单
        form:{
          checkedDatabaseNames: ['Rmgb'],
          checkedType:'1'
        },
        // 表单校验
        rules: {
          adress: [
            { required: true, message: "请输入数据库地址", trigger: "blur" }
          ],
          user: [
            { required: true, message: "请输入登录名", trigger: "blur" }
          ],
          password: [
            { required: true, message: "请输入登录密码", trigger: "blur" }
          ],
        }
      };
    },
    created() {
      this.getTableList();
    },
    methods: {
      clickRow(row) {
        this.$refs.table.toggleRowSelection(row);
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.sysids = selection.map(item => item.sysid);
        this.multiple = !selection.length;
      },
      // 查询表数据
      getTableList() {
        listMdlsTable(this.tableParams).then(res => {
          if (res.code === 200) {
            let data = res.rows;
            let treeAry = [];
            for (let i in data) {
              let v = data[i];
              let node = {};
              node.label = v.tableName;
              node.value = v.tableName;
              treeAry.push(node);
            }
            this.tableOptions = treeAry;
            this.oldtableOptions = treeAry;
          }
        });
      },
      //自适应宽度
      linefeed (h,{column,index}) { // column,index都是el-table中自带的
        let number = column.label.length // 表头字数
        let size = 16 // 字体尺寸
        column.minWidth = number*size // 计算宽度
        return h('div',{class:'table-head',style:{width:'100%'}},[column.label])
      },
      //表名称变更
      tableSelect(val){
        this.queryParams.tableName = val;
        this.queryParams.pageNum = 1;
        this.queryParams.pageSize = 100;
        listMdlsColumn(this.queryParams).then(res => {
          if (res.code === 200) {
            let data = res.rows;
            let treeAry = [];
            for(let i in data){
              let v = data[i];
              let node = {};
              node.label = v.columnComment;
              node.property = v.columnName.toLowerCase();
              treeAry.push(node);
            }
            this.shows=true;
            this.tableHead = treeAry;
          }
        });
        this.getList();
      },
      //源数据表变更获取字段信息
      oldTableSelect(val){
        //根据待导入表名称获取最大sysid
        maxSysId(val).then(res => {
          if (res.code === 200) {
            if(res.data != null){
              this.form.startSysId = res.data;
              this.form.endSysId = res.data + 1;
            }else{
              this.form.startSysId = 0;
              this.form.endSysId = 1;
            }
          }
        });
      },
      //待导入数据表变更获取字段信息
      newTableSelect(val){
        let queryString = {};
        queryString.tableName = val;
        queryString.pageNum = 1;
        queryString.pageSize = 100;
        listMdlsColumn(queryString).then(res => {
          if (res.code === 200) {
            let data = res.rows;
            let treeAry = [];
            for(let i in data){
              let v = data[i];
              let node = {};
              node.label = v.columnName;
              node.value = v.columnName;
              treeAry.push(node);
            }
            this.newColumnOptions = treeAry;
          }
        });
      },
      getList(){
        allList(this.queryParams).then(res => {
          if (res.code === 200) {
            this.dbTableList = res.rows;
            this.total = res.total;
          }
        });
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      /** 同步按钮操作 */
      handleSyc(){
        this.open = true;
      },
      //按条件查询
      sycChange(val){
        if(val === '2'){
          this.dis = false;
          this.form.startSysId = 1;
          this.form.endSysId = 2;
        }else{
          this.dis = true;
          this.form.startSysId = null;
          this.form.endSysId = null;
        }
      },
      // 判断结束是否小于开始
      endPosition(val){
        if(this.form.startSysId === "" || this.form.startSysId === undefined){
          this.$modal.msgError("请先选择待导入数据库表!");
          this.form.endSysId = "";
        }
        if(val <= this.form.startSysId){
          this.$modal.msgError("结束位置不能小于开始位置!");
          this.form.endSysId = this.form.startSysId + 1;
        }
      },
      handleCheckAllChange(val) {
        this.form.checkedDatabaseNames = val ? checkedtableOptions : [];
        this.isIndeterminate = false;
      },
      handleCheckedTablesChange(value) {
        let checkedCount = value.length;
        this.checkAll = checkedCount === this.checktableNames.length;
        this.isIndeterminate = checkedCount > 0 && checkedCount < this.checktableNames.length;
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.sycDisabled = false;
        this.reset();
      },
      //关闭页面清空
      clo() {
        this.open = false;
        this.result = null;
        this.sycDisabled = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.result = null,
        this.form = {
          adress: null,
          user: null,
          password: null,
          checkedDatabaseNames: ['Rmgb'],
          checkedType: '1'
        };
        this.resetForm("form");
      },
      getCurrentTime() {
        //获取当前时间并打印
        var _this = this;
        let yy = new Date().getFullYear();
        let mm = new Date().getMonth()+1;
        let dd = new Date().getDate();
        let hh = new Date().getHours();
        let mf = new Date().getMinutes()<10 ? '0'+new Date().getMinutes() : new Date().getMinutes();
        let ss = new Date().getSeconds()<10 ? '0'+new Date().getSeconds() : new Date().getSeconds();
        _this.gettime = yy+'/'+mm+'/'+dd+' '+hh+':'+mf+':'+ss;
        return _this.gettime;
      },
      /** 提交按钮 */
      submitForm() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            this.sycDisabled = true;
            //插入同步时间
            this.result = "开始同步时间：" + this.getCurrentTime() +"\r";
            this.result += "开始创建数据库连接：\r";
            //数据同步
            this.subDataBaseInfo();
          }
        });
      },
      /** 数据同步 */
      async subDataBaseInfo(){
        await this.connectDatabases();
        //await this.getCount();
      },
      /** 创建数据库连接 */
      async connectDatabases() {
        this.form.checkedDatabaseNames = this.form.checkedDatabaseNames.join(",");
        connectDatabase(this.form).then(res => {
          if(res.msg === 'fail'){
            this.result += "数据库连接超时或用户名密码错误，请重试！\r";
          }else{
            this.result += "数据库连接成功！\r";
            this.getCount();
          }
          this.sycDisabled = false;
        });
      },
      /** 查询数据量 */
      async getCount() {
        var databases = this.form.checkedDatabaseNames.split(",");
        for(let i = 0; i < databases.length; i++){
            this.form.databaseName = databases[i];
            connectCount(this.form).then(res => {
              if(res.msg === 'fail'){
                this.result += databases[i] + "数据库连接失败！\r";
              }else{
                this.result +=  databases[i] + "总计数据量:" +res.data.count +"条------已同步到:" + res.data.sysIdMaX +"\r";
              }
            });
        };
        console.log(this.form);
        sycDataBaseResource(this.form).then(res => {
        });
      }
    }
  };
</script>
